<script setup lang="ts">
import {  loginPasswordAPI } from '@/api/common'
import { useUserStore } from '@/store/user'
import type { PostLoginPasswordParams } from '@/types/common'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

const form = ref<PostLoginPasswordParams>({
  mobile: '13230000049',
  password: 'abc12345',
})

const isAgree = ref(false)

const rules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { pattern: /^[a-zA-Z0-9]{6,20}$/, errorMessage: '请输入正确的密码' },
    ],
  },
})

const formRef = ref<UniHelper.UniFormsInstance>()

const handleLogin = async () => {
  try {
    if (!isAgree.value) {
      uni.showToast({
        title: '请同意用户协议和隐私协议',
        icon: 'none',
      })
      return
    }
    await formRef.value?.validate?.()

    const res = await loginPasswordAPI(form.value)
    // console.log(res)
    // 存储到pinia
    const userStore = useUserStore()
    userStore.setToken(res.token)
    userStore.setUserInfo(res)
    // 跳转到主页
    uni.showToast({ title: '登录成功!' })
    uni.switchTab({
      url: '/pages/index/index',
    })
  } catch (error) {
    console.log(error)
  }
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :rules="rules" :model="form">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="form.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="form.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="handleLogin">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
@import './styles.scss';
</style>
